package com.flyone.fuxiao.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.XML;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: text-to-picture
 * @ClassName: GptUtils
 * @description: 获取openAI的返回信息
 * @author: banyun
 * @create: 2024-04-01 11:19
 */
@Component
public class GptUtils {
    // 获取openAI的返回信息
    /**
     * 聊天端点
     */
    String chatEndpoint = "https://api.953959.xyz/v1/chat/completions";
    /**
     * api密匙
     */
    String apiKey = "sk-JKOsGwxioMS2Hh9fF553D222A54244F2Bf26707b8a133b1f";

    /**
     * 发送消息
     *
     * @param txt 内容
     * @return {@link String}
     */
    public String chat(String txt) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("model", "gpt-3.5-turbo");
        List<Map<String, String>> dataList = new ArrayList<>();
        dataList.add(new HashMap<String, String>() {{
            put("role", "user");
            put("content", txt);

        }});
        paramMap.put("messages", dataList);
        try {
            // ...
            String body = HttpRequest.post(chatEndpoint)
                    .header("Authorization", apiKey)
                    .header("Content-Type", "application/json")
                    .body(JsonUtils.toJson(paramMap))
                    .execute()
                    .body();
            System.out.println("从https://api.953959.xyz返回的响应：" + body);  // 打印响应内容

            // 检查响应的code字段
            JSONObject jsonObject = new JSONObject(body);
            int code = jsonObject.getInt("code");
            if (code == -1) {
                String message = jsonObject.getStr("message");
                throw new RuntimeException("服务器错误: " + message);
            }
            // 解析text/event-stream响应
            String[] events = body.split("\n\n");
            StringBuilder contentBuilder = new StringBuilder();
            for (String event : events) {
                if (event.startsWith("data: ")) {
                    String data = event.substring(6);
                    JSONArray choices = jsonObject.getJSONArray("choices");
                    JSONObject result = (JSONObject) choices.get(0);
                    JSONObject delta = result.getJSONObject("delta");
                    String content = delta.getStr("content");
                    contentBuilder.append(content);
                }
            }
            String content = contentBuilder.toString();

            // 将content转换为JSON对象
            JSONObject json = XML.toJSONObject(content);
            String jsonString = json.toString();
            System.out.println("JSON 字符串: " + jsonString);  // 打印JSON字符串
            return jsonString;
        } catch (Exception e) {
            e.printStackTrace();  // 打印出异常的堆栈跟踪
            return "出现了异常";
        }
    }
}



